<template>
  <div style="" class="ScoreManageStyle">
    <el-radio-group v-if="fatherName!=='分诊'" v-model="chelaxy" style="margin-left:15px" @change="clearPage();selectList()">
      <el-radio-button v-if="!(this.$store.getters.hospitalId == 76 || this.$store.getters.hospitalId == 201)" label="胸痛" />
      <el-radio-button label="卒中" />
    </el-radio-group>
    <!-- <el-divider /> -->
    <el-row style="margin-top: 10px;">
      <el-col :span="20" style="font-size: 14px;margin-left: 10px">
        评分类型:
        <el-select v-model="targetType">
          <el-option value="single" label="single" />
          <el-option value="order" label="order" />
        </el-select>
      </el-col>
      <el-col :span="1"><el-button type="primary" @click="clearPage();selectList()">查询</el-button></el-col>
      <el-col :span="1" :offset="1">
        <el-button
          type="primary"
          @click="
            dialogNature = '新增';
            add_or_modify_dialogVisible = true;
            resetForm('classAdata');
          "
        >
          新增
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col style="padding: 20px;">
        <el-table ref="tableData" :data="tableData" height="700" style="width: 100%; " class="table" border>
          <el-table-column label="评分" min-width="150" prop="name" header-align="center" align="center" />
          <el-table-column label="名称" prop="type" min-width="150" header-align="center" align="center" />
          <el-table-column label="状态" prop="status" width="100" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status == '1'">使用中</span>
              <span v-if="scope.row.status == '0'">禁用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.defaultFlag!=0">
                <el-button v-if="scope.row.status == '1'" type="text" @click="updateClassAStatus(scope.row)">禁用</el-button>
                <el-button v-if="scope.row.status == '0'" type="text" @click="updateClassAStatus(scope.row)">启用</el-button>
                <!-- <el-button type="text" class="ml-10"@click="details(scope.row, scope.$index)">详情</el-button> -->
              </span>

              <el-button type="text" :class="{ 'ml-10' : scope.row.defaultFlag !=0 }" @click="openAdd(scope.row, scope.$index)">预览</el-button>
              <span v-if="scope.row.defaultFlag != 0">
                <el-button type="text" class="ml-10" @click="details(scope.row, scope.$index)">详情</el-button>
              </span>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="float: right"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
    <!-- 增改评分主弹窗 -->
    <el-dialog
      :title="dialogNature + '评分'"
      :visible.sync="add_or_modify_dialogVisible"
      width="80%"
      top="15px"
      custom-class="add_or_modify_dialogStyle"
      :before-close="classAHandleClose"
      :destroy-on-close="true"
    >
      <el-scrollbar style=" height: 100%" class="scrollbarStyle">
        <el-form ref="classAdata" :model="classAdata" :rules="classARules" :inline="true" label-width="80px" class="demo-ruleForm">
          <!-- v-show="false" -->
          <el-form-item v-show="false" v-if="dialogNature=='修改'" label="id" prop="id"><el-input v-model="classAdata.id" disabled placeholder="请输入" /></el-form-item>
          <el-form-item label="评分名称" prop="name"><el-input v-model="classAdata.name" placeholder="请输入" label-suffix="'大 啊'" /></el-form-item>
          <el-form-item label="评分类型" prop="type">
            <el-select v-model="classAdata.type" :disabled="!!classAdata.id">
              <el-option value="single" label="single" />
              <el-option value="order" label="order" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="评分状态" prop="status">
          <el-select v-model="classAdata.status" :disabled="dialogNature == '修改' || classFinish">
            <el-option value="1" label="使用中" />
            <el-option value="0" label="禁用" />
          </el-select>
        </el-form-item> -->
          <el-form-item v-if="!classAdata.id" class="fr mr-10"><el-button type="primary" @click="saveClassA('classAdata')">新增评分</el-button></el-form-item>
          <el-form-item v-if="!!classAdata.id" class="fr mr-10"><el-button type="primary" @click="updateClassAinfo('classAdata')">修改评分</el-button></el-form-item>
        </el-form>
        <el-divider class="mt-10" />
        <el-row class="scoreAddUpStyle">
          <el-col v-if="!!classAdata.id && classAdata.type == 'order'" :xl="3" :lg="4" :sm="5" style=" height: 100%">
            <el-scrollbar style=" height: 100%" class="scrollbarStyle">
              <el-card class="box-card" shadow="hover" :body-style="{ padding: '0px', textAlign: 'center' }" style=" height: 100%">
                <div slot="header" class="clearfix">
                  <span>项目</span>
                  <el-button style="float: right; padding: 3px 0" type="text" @click="transferCurrentInfo('2', '新增', null, classAdata.id, 'title')">新增项目</el-button>
                </div>
                <div class="classbBtnGroup">
                  <p v-for="(item, index) in classBdata" :key="index">
                    <el-radio v-model="classBradioValue" :label="item" name="classBradio" border style="width: 110px;" @change="collapseClose()">{{ item.name }}</el-radio>
                    <el-button type="text" icon="el-icon-edit" circle size="mini" @click="transferCurrentInfo('2', '修改', item, null, 'title')" />
                  <!-- <el-button type="primary" icon="el-icon-edit" circle size="mini" /> -->
                  </p>
                </div>
              </el-card>
            </el-scrollbar>
          </el-col>
          <el-col v-if="bOrB2C(classBdata).length > 0" :xl="21" :lg="20" :sm="19" :offset="classAdata.type == 'single' ? 2 : 0" style=" height: 100%">
            <el-scrollbar style=" height: 100%" class="scrollbarStyle">
              <el-card class="box-card" shadow="hover" :body-style="{ height: '100%' }" style=" height: 100%">
                <subComponents v-if="classBdata.length > 0" ref="scoreChild" :score-data="bOrB2C(classBdata)" :parent-info="classBinfo" @addItemTofather="filialBack" />
              </el-card>
            </el-scrollbar>
          </el-col>
        </el-row>
        <el-divider />
        <el-row v-if="classBdata.length > 0" class="mt-10 pt-5">
          <el-form ref="conclusionForm" :model="conclusionForm" :rules="conclusionRules" :inline="true" label-width="80px" class="demo-ruleForm">
            <!-- v-show="false" -->
            <!-- <el-form-item label="id" prop="id"><el-input v-model="conclusionForm.id" disabled placeholder="请输入" /></el-form-item> -->
            <el-form-item label="排序序号" prop="showIndex"><el-input v-model.number="conclusionForm.showIndex" placeholder="请输入序号" /></el-form-item>
            <span class="relationStyle">
              <el-form-item label="范围区间" prop="mincondition">
                <el-select v-model="conclusionForm.mincondition" placeholder="最小判断条件" clearable>
                  <el-option value=">" label=">" />
                  <el-option value=">=" label=">=" />
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="minimum">
                <el-input v-model="conclusionForm.minimum" placeholder="请输入最小值" @input="conclusionForm.minimum=conclusionForm.minimum.replace(/[^\d]/g, '')" />
              </el-form-item>
              <span style="line-height:36px;padding-right: 5px;">-</span>
              <el-form-item label="" prop="maxcondition">
                <el-select v-model="conclusionForm.maxcondition" placeholder="最大判断条件" clearable>
                  <el-option value="<" label="<" />
                  <el-option value="<=" label="<=" />
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="maximum"><el-input v-model="conclusionForm.maximum" placeholder="请输入最大值" @input="conclusionForm.maximum=conclusionForm.maximum.replace(/[^\d]/g, '')" /></el-form-item>
            </span>
            <el-form-item class="fr mr-10"><el-button type="primary" @click="addConclusion('conclusionForm')">添加判断</el-button></el-form-item>
            <el-form-item label="结论描述" prop="conclusion" class="conclusionStyle" style="width: 100%;display: block;">
              <el-input v-model="conclusionForm.conclusion" placeholder="请输入结论描述" />
            </el-form-item>
          </el-form>
          <!-- zhelizheli -->
          <el-table :data="conclusionTableData" border style="width: 100%">
            <el-table-column prop="showIndex" label="序号" width="180" align="center" />
            <el-table-column prop="name" label="范围" width="180" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.mincondition }}{{ scope.row.minimum }} ，{{ scope.row.maxcondition }}{{ scope.row.maximum }}</span>
              <!-- <el-button type="text" @click="details(scope.row, scope.$index)">详情</el-button> -->
              </template>
            </el-table-column>
            <el-table-column prop="conclusion" label="描述" align="center" />
            <el-table-column label="操作" width="50" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="deleteScoreConclusion(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click=" add_or_modify_dialogVisible = false; resetForm('classAdata'); " > 关闭 </el-button>
      </span> -->
      </el-scrollbar>
    </el-dialog>
    <!-- 增改评分主弹窗 - End -->

    <!-- 增改评分项目小弹窗  -->
    <el-dialog
      width="30%"
      class="dialogStyle"
      :title="currentInfo.currentType + '项目'"
      :visible.sync="new_title_dialogVisiblet"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="classXHandleClose"
      :destroy-on-close="true"
      append-to-body
    >
      <el-form ref="addOrUpdateProjectData" :model="addOrUpdateProjectData" :rules="classXRules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="项目名称" prop="name"><el-input v-model="addOrUpdateProjectData.name" placeholder="请输入项目名称" /></el-form-item>
        <el-form-item label="排序序号" prop="showIndex">
          <el-input v-model.number="addOrUpdateProjectData.showIndex" type="age" autocomplete="off" placeholder="请输入项目序号" />
        </el-form-item>
        <el-form-item label="项目类型" prop="fieldType">
          <!-- <el-select v-model="addOrUpdateProjectData.fieldType" placeholder="请选择项目类型" :disabled="currentInfo.currentType == '修改' || (currentInfo.currentLevel === '2'&&classAdata.type === 'order')"> -->
          <el-select v-model="addOrUpdateProjectData.fieldType" placeholder="请选择项目类型" disabled>

            <el-option value="title" label="标题" />
            <el-option value="content" label="内容" />
          </el-select>
        </el-form-item>
        <!-- && currentInfo.currentLevel=='2' -->
        <el-form-item v-if="addOrUpdateProjectData.fieldType == 'title'" label="显示得分" prop="hasScore">
          <el-radio-group v-model="addOrUpdateProjectData.hasScore" :disabled="currentInfo.currentType == '修改'">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            new_title_dialogVisiblet = false;
            classXHandleClose();
          "
        >
          取消
        </el-button>
        <el-button type="primary" @click="saveClassX('addOrUpdateProjectData', currentInfo)">{{ currentInfo.currentType }}</el-button>
      </span>
    </el-dialog>
    <!-- 增改评分项目小弹窗 -End -->
    <!-- 增改评分条目小弹窗  -->
    <el-dialog
      width="30%"
      class="dialogStyle"
      :title="currentInfo.currentType + '条目'"
      :visible.sync="new_content_dialogVisiblet"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="classXHandleClose"
      :destroy-on-close="true"
      append-to-body
    >
      <el-form ref="addOrUpdateProjectData" :model="addOrUpdateProjectData" :rules="classXRules" label-width="100px" class="demo-ruleForm">
        <!-- <el-form-item label="项目名称" prop="name"><el-input v-model="addOrUpdateProjectData.name" placeholder="请输入项目名称" /></el-form-item> -->
        <el-form-item label="序号" prop="showIndex">
          <el-input v-model.number="addOrUpdateProjectData.showIndex" type="age" autocomplete="off" placeholder="请输入条目序号" />
        </el-form-item>
        <el-form-item label="得分" prop="score"><el-input v-model.number="addOrUpdateProjectData.score" type="age" autocomplete="off" placeholder="请输入条目得分" /></el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addOrUpdateProjectData.type" placeholder="请选择条目类型" @change="addOrUpdateProjectData.groupIndex='' ">
            <el-option value="1" label="单选" />
            <el-option value="2" label="多选" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="addOrUpdateProjectData.type == '1'" label="组别" prop="groupIndex">
          <el-input v-model="addOrUpdateProjectData.groupIndex" placeholder="请输入组别名称(相同组别名的单选为同组)" />
        </el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="addOrUpdateProjectData.name" type="textarea" placeholder="请输入描述名称" /></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            new_content_dialogVisiblet = false;
            classXHandleClose();
          "
        >
          取消
        </el-button>
        <el-button type="primary" @click="saveClassX('addOrUpdateProjectData', currentInfo)">{{ currentInfo.currentType }}</el-button>
      </span>
    </el-dialog>
    <!-- 增改评分条目小弹窗 -End -->

    <!-- 预览评分 -->
    <el-dialog
      title="评分预览"
      :visible.sync="openAddDialog"
      custom-class="estimateAddDialog"
      width="75%"
      top="15px"
      :before-close="handleClose"
      center
    >
      <div style="max-height: 80vh;overflow: auto;">
        <el-row v-for="(item,index) in list" :key="item.index + index" :style="border" class="card">
          <el-row class="card-title" style="margin-bottom: 20px" type="flex">
            <el-col :sm="10" class="content"> {{ item.name }} </el-col>
            <el-col :sm="14">
              <span v-if="addMark" style="margin-right: 30px">
                得分：{{ addMark }}
              </span>
              <span v-if="addGrade">等级：{{ addGrade }}</span>
            </el-col>
          </el-row>
          <row
            v-if="!item.fieldType || item.fieldType != 'content'"
            :list="item.scoreClassList"
            @dataEmit="getAddGrade(item)"
          />
          <check
            v-if="!item.fieldType || item.fieldType != 'content'"
            v-model="item.data"
            :list="item.scoreClassList"
            style="padding-left: 30px"
            @dataEmit="getAddGrade(item)"
          />
        </el-row>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="addConfirm"> 关 闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectScoreClassAll,
  saveScoreClassA,
  updateScoreClassA,
  saveOrUpdateScoreClassX,
  selectScoreConclusion,
  deleteScoreConclusion,
  saveOrUpdateScoreConclusion
} from '@/api/back-management/greenway-set/Score_management'
import SubComponents from '@/components/ScoreManagement/SubComponents'
import Check from '@/components/scoreRow/Check'
import Row from '@/components/scoreRow/Row'
export default {
  name: 'ScoreManage',
  components: { SubComponents, Row, Check },
  props: {
    fatherName: {
      type: String,
      // required: true,
      default() {
        return '胸痛'
      }
    }
  },
  data() {
    const validateScope = (rule, value, callback) => {
      const findFriend = {
        minimum: 'mincondition',
        mincondition: 'minimum',
        maximum: 'maxcondition',
        maxcondition: 'maximum'
      }
      const explains = {
        minimum: '最小值',
        mincondition: '最小判断条件',
        maximum: '最大值',
        maxcondition: '最大判断条件'
      }
      const data = this.conclusionForm
      const oneself = value // 当前字段值
      const crew = data[findFriend[rule.fullField]]// 同组队友值
      let val = 'minimum'; let condition = 'mincondition'
      if (rule.fullField === 'minimum' || rule.fullField === 'mincondition') { // 取对组名
        val = 'maximum'
        condition = 'maxcondition'
      }
      if (crew || crew.toString() === 0) { // 组员有值
        if (oneself || oneself.toString() === 0) { // 当前有值
          if ((!data[val] && !(data[val] === 0)) && !data[condition]) {
            this.$refs.conclusionForm.validateField([val, condition]) // 更新另一组校验状态
          }
          callback()
        } else { // 当前没有值
          callback(new Error(explains[rule.fullField] + '不能为空')) // 当前不能为空
        }
      } else { // 同组队友没有值
        if (oneself || oneself.toString() === 0) { // 但当前有值
          this.$refs.conclusionForm.validateField(findFriend[rule.fullField]) // 验证队友
        } else { // 当前没有值
          // 判断另一组是否成立
          if ((data[val] || data[val] === 0) && data[condition]) {
            callback()
          } else { // 对方不成对
            callback(new Error('最少选填一组边界值'))
          }
        }
      }
    }
    return {
      chelaxy: (this.$store.getters.hospitalId == '76' || this.$store.getters.hospitalId == '201') ? '卒中' : '胸痛',
      tableData: [],
      /* 表格分页参数*/
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0,
      userId: this.$store.getters.userId,
      hospitalId: this.$store.getters.hospitalId,
      apiToken: this.$store.getters.apiToken,
      targetType: 'order',
      dialogNature: '新增',
      // dialogNature:{
      //   add: '新增',
      //   modify: '修改',
      // }
      classARules: {

        id: [{ required: true, message: '无id', trigger: 'blur' }],
        name: [{ required: true, message: '请输入评分名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择评分类型', trigger: 'change' }],
        status: [{ required: true, message: '请选择评分状态', trigger: 'change' }]
      },

      conclusionRules: {
        showIndex: [{ required: true, message: '序号不能为空' }, { type: 'number', message: '序号必须为数字值' }],
        minimum: [
          { validator: validateScope, trigger: 'blur' }
          // { type: 'number', message: '最小值必须为数字值' }
        ],
        maximum: [
          // { required: true, message: '最大值不能为空' },
          { validator: validateScope, trigger: 'blur' }
          // { type: 'number', message: '最大值必须为数字值' }
        ],
        mincondition: [
          { validator: validateScope, trigger: 'change' }
          // { required: true, message: '请选择最小判断条件', trigger: 'change' },
        ],
        maxcondition: [
          { validator: validateScope, trigger: 'change' }
          // { required: true, message: '请选择最大判断条件', trigger: 'change' },
        ],
        conclusion: [{ required: true, message: '请输入结论描述', trigger: 'blur' }]
      },

      classXRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        showIndex: [{ required: true, message: '序号不能为空' }, { type: 'number', message: '序号必须为数字值' }],
        fieldType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
        score: [{ required: true, message: '请输入得分', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        hasScore: [{ required: true, message: '请选择是否显示得分', trigger: 'change' }],
        groupIndex: [{ required: true, message: '请输入组别', trigger: 'change' }]
      },
      add_or_modify_dialogVisible: false, // 新增修改评分弹出框标识
      new_title_dialogVisiblet: false, // 新增修改项目弹出框标识
      new_content_dialogVisiblet: false, // 新增修改条目弹出框标识
      scoreClassAllData: [], // 查询所有评分数据
      scoreArr: ['scoreClassAList', 'scoreClassBList', 'scoreClassCList', 'scoreClassDList', 'scoreClassEList'],
      addOrUpdateProjectData: {
        id: '',
        parentsId: '', // 父级id
        name: '', // 项目名称
        showIndex: '', // 排序序号
        flag: '1', // "1"有下级 "0"无下级
        fieldType: 'title', //  "title"或者"content"
        type: '', // 项目类型
        hasScore: '', // 显示得分
        groupIndex: '' // 单选分组序号
      },
      classAdata: {
        id: '',
        name: '',
        type: '',
        status: '0'
      },
      classBdata: [],
      classBradioValue: '',
      currentInfo: {
        // 当前等级,用来确定弹窗保存数据的层级
        currentLevel: '',
        currentType: '' // 新增或修改
      },
      classBinfo: {
        type: '', // single || order
        classLevel: '', // 传给子组件的等级,递归定位使用
        classAIsSingle: ''
      },
      classLevel: '', // 传给子组件的等级,递归定位使用
      parentData: [],
      conclusionForm: {
        // hospitalId:this.$store.getters.hospitalId,
        // userId
        showIndex: '', // 排序序号
        scoreId: '', // 对应scoreClassA的数据id
        mincondition: '', // 最小判断条件
        maxcondition: '', // 最大判断条件
        minimum: '', // 最小值
        maximum: '', // 最大值
        conclusion: '' // 结论名
      },
      conclusionTableData: [], // 结论表格

      // 预览
      openAddDialog: false,
      list: [],
      addGrade: '',
      addMark: '',
      border: {
        border: '1px dashed #DCDFE6',
        'border-radius': '4px',
        'margin-bottom': '20px',
        'padding-top': '10px',
        'padding-left': '30px'
      }
    }
  },
  created() {
    console.log(this.$store.getters.hospitalId, 'hospitalId')
    console.log(this.fatherName, 'fatherName')
    // this.chelaxy = this.fatherName === '分诊' ? '分诊' : '胸痛'
    // console.log(this.fatherName + '评分管理')
    this.selectList()
  },
  methods: {

    /*
      保存一级评分(A)
    */
    saveClassA(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // alert('submit!')
          const data = {
            name: this.classAdata.name,
            type: this.classAdata.type,
            status: '0',
            hospitalId: this.hospitalId,
            userId: this.userId,
            greenType: this.chelaxy
          }
          saveScoreClassA(data)
            .then(res => {
              if (res.code === 0) {
                this.$message.success('新增成功')
                this.classAdata.id = res.data
                if (this.classAdata.type === 'single') {
                  const params = {
                    pageNum: 1,
                    pageSize: 1,
                    greenType: this.chelaxy,
                    hospitalId: this.hospitalId,
                    type: this.targetType,
                    scoreId: this.classAdata.id
                  }
                  selectScoreClassAll(params).then(data => {
                    this.classBdata = [data.data.list[0]]
                  })
                }
                this.selectList()
              } else {
                this.$message.error('新增失败')
              }
            })
            .catch(err => {
              console.log('err: ', err)
              this.$message.error('新增失败')
            })

          this.selectList()
          // this.new_title_dialogVisiblet = false
          // this.resetForm(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 更改一级评分状态
    updateClassAStatus(row) {
      const data = {
        id: row.id,
        hospitalId: row.hospitalId,
        greenType: row.greenType,
        name: row.name,
        type: row.type,
        userId: this.userId,
        status: row.status === '1' ? '0' : '1'
      }
      updateScoreClassA(data)
        .then(res => {
          if (res.code === 0) {
            this.$message.success('修改成功')
            this.selectList()
          } else {
            this.$message.error('修改失败')
          }
        })
        .catch(err => {
          console.log('err: ', err)
          this.$message.error('修改失败')
        })
    },
    // 更改一级评分
    updateClassAinfo(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const data = {
            id: this.classAdata.id,
            name: this.classAdata.name,
            type: this.classAdata.type,
            status: this.classAdata.status,
            hospitalId: this.hospitalId,
            userId: this.userId,
            greenType: this.chelaxy
            // flag: '1', // "1"有下级 "0"无下级
            // fieldType: 'title', //  "title"或者"content"
          }
          updateScoreClassA(data)
            .then(res => {
              if (res.code === 0) {
                this.$message.success('修改成功')
                this.selectList()
              } else {
                this.$message.error('修改失败')
              }
            })
            .catch(err => {
              console.log('err: ', err)
              this.$message.error('修改失败')
            })
          this.selectList()
          // this.new_title_dialogVisiblet = false
          // this.resetForm(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /* 保存二级评分(B)*/
    saveClassB(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.new_title_dialogVisiblet = false
          this.resetForm(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /*
     *保存X级评分
     * formName:表单ref
     * currentType:当前状态(新增或修改)
     */
    collapseClose() {
      this.$refs.scoreChild && this.$refs.scoreChild.collapseReseat()
    },
    // 保存后a->b同步问题
    // 数据下潜问题

    saveClassX(formName, info) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const saveFunc = {
            // '1': 'saveScoreClassA',
            '2': 'saveScoreClassB',
            '3': 'saveScoreClassC',
            '4': 'saveScoreClassD',
            '5': 'saveScoreClassE'
          }
          const updateFunc = {
            // '1': 'updateScoreClassA',
            '2': 'updateScoreClassB',
            '3': 'updateScoreClassC',
            '4': 'updateScoreClassD',
            '5': 'updateScoreClassE'
          }
          let pickFunc = {}
          if (info.currentType === '新增') {
            pickFunc = saveFunc
          } else if (info.currentType === '修改') {
            pickFunc = updateFunc
          }
          this.addOrUpdateProjectData.flag = this.addOrUpdateProjectData.fieldType === 'title' ? '1' : '0'
          const data = JSON.parse(JSON.stringify(this.addOrUpdateProjectData))
          saveOrUpdateScoreClassX(pickFunc[info.currentLevel], data)
            .then(res => {
              if (res.code === 0) {
                const params = {
                  pageNum: this.pageNum,
                  pageSize: this.pageSize,
                  greenType: this.chelaxy,
                  hospitalId: this.hospitalId,
                  type: this.targetType,
                  scoreId: this.classAdata.id
                }
                selectScoreClassAll(params).then(res => {
                  if (this.classAdata.type === 'order') {
                    const classBList = res.data.list[0].scoreClassBList
                    this.classBdata = this.compare(classBList, 'showIndex')
                  } else {
                    this.classBdata = [res.data.list[0]]
                  }
                  this.$message.success(info.currentType + `成功`)
                })
              } else {
                this.$message.error(info.currentType + `失败`)
              }
              this.selectList()
              this.new_title_dialogVisiblet = false
              this.new_content_dialogVisiblet = false
              // if(property === "title"){
              //   this.new_title_dialogVisiblet = true
              // }
              // if(property === "content"){
              //   this.new_content_dialogVisiblet = true
              // }
            })
            .catch(err => {
              console.log('err: ', err)
              this.$message.error(info.currentType + `失败`)
            })

          // this.resetForm(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 新增修改项目时记录层级,激活弹窗 [并回显]
    transferCurrentInfo(level, type, item, parentsId, property) {
      // console.log(level, type, item)
      this.currentInfo = {
        // 当前等级,用来确定弹窗保存数据的层级
        currentLevel: level,
        currentType: type // 新增或修改
      }

      this.clearXData()
      if (type === '修改') {
        this.addOrUpdateProjectData = {
          id: item.id,
          parentsId: item.parentsId, // 父级id
          name: item.name, // 项目名称
          showIndex: parseInt(item.showIndex) || '', // 排序序号
          fieldType: item.fieldType, //  "title"或者"content"
          flag: item.flag, // "1"有下级 "0"无下级
          // flag: item.fieldType === 'title' ? '1' : '0', // "1"有下级 "0"无下级
          type: item.type, // 项目类型
          score: item.score, // 得分
          hasScore: item.hasScore.toString(), // 显示得分
          groupIndex: item.groupIndex // 单选分组序号
        }
      } else if (type === '新增') {
        // if (this.currentInfo.currentLevel === '2' && this.classAdata.type === 'order') {
        this.addOrUpdateProjectData.flag = '1'
        this.addOrUpdateProjectData.fieldType = 'title'
        // }
        this.addOrUpdateProjectData.parentsId = parentsId
      }
      // if (this.currentInfo.currentLevel === '2' && this.currentInfo.currentType === '新增' &&this.classAdata.type === 'order') {
      //   this.addOrUpdateProjectData.flag = '1'
      //   this.addOrUpdateProjectData.fieldType = 'title'
      // }

      if (property === 'title') {
        this.new_title_dialogVisiblet = true
      }
      if (property === 'content') {
        this.addOrUpdateProjectData.fieldType = property
        this.new_content_dialogVisiblet = true
      }
    },

    /* 根据评分类型筛选数据*/
    bOrB2C(data) {
      if (this.classAdata.type === 'order') {
        // 过滤数据-----
        const dataArr = []
        data.forEach(el => {
          if (this.classBradioValue.id === el.id) {
            // console.log(this.classBradioValue, 111, el.id)
            this.classBinfo.type = el.fieldType
            this.classBinfo.classLevel = '2'
            dataArr.push(el)
          }
        })
        return dataArr
      } else if (this.classAdata.type === 'single') {
        // if (this.classAdata.type === 'single')
        // console.log(123, this.classAdata)

        this.classBinfo.type = 'title'
        this.classBinfo.classAIsSingle = true
        if (data.length) {
          data[0].flag = '1' // "1"有下级 "0"无下级
          data[0].fieldType = 'title' //  "title"或者"content"
        }
        return data
      } else {
        return []
      }
    },
    filialBack(data) {
      // console.log('接收回传', data)
      const { level, type, item, parentsId, property } = data
      this.transferCurrentInfo(level, type, item, parentsId, property)
    },

    // 外层表格查看详情/修改
    details(row, index) {
      this.dialogNature = '修改'
      this.add_or_modify_dialogVisible = true
      this.$nextTick(() => {
        // this.resetForm('classAdata')
        const { id, name, type, status } = row
        this.classAdata = { id, name, type, status }

        if (this.classAdata.type === 'order') {
          const classBList = row.scoreClassBList
          this.classBdata = this.compare(classBList, 'showIndex')
          if (classBList && classBList.length > 0) {
          // A层为order类型
            this.classBradioValue = classBList[0]
            this.classBinfo.classLevel = '2'
          } else {
            this.classBinfo.classLevel = '3'
          }
        } else {
          this.classBdata = [row]
          this.classBinfo.classLevel = '1'
        }
        // console.log('classB', this.classBdata)
        this.selectScoreConclusionFun()
      })
    },
    selectScoreConclusionFun() {
      const params = {
        hospitalId: this.hospitalId,
        scoreId: this.classAdata.id
        // pageNum: '1',
        // pageSize: '10'
      }
      this.conclusionForm.id = this.classAdata.id
      selectScoreConclusion(params).then(res => {
        this.conclusionTableData = res.data.list
      })
    },

    // 排序
    compare(data, key) {
      data.sort((a, b) => {
        const value1 = parseInt(a[key]) || 0
        const value2 = parseInt(b[key]) || 0
        // console.log(value1, value2, value1 - value2)
        return value1 - value2 // 升序,降序为value2 - value1
      })
      return data
    },
    /* 查询列表*/
    selectList() {
      const data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        greenType: this.chelaxy,
        hospitalId: this.hospitalId,
        type: this.targetType
      }
      selectScoreClassAll(data).then(res => {
        this.tableData = res.data.list
        this.pageTotal = res.data.total
      })
    },
    clearPage() {
      this.pageNum = 1
      this.pageSize = 10
      this.pageTotal = 0
    },
    // 清除小弹窗数据
    clearXData() {
      this.resetForm('addOrUpdateProjectData')
      this.addOrUpdateProjectData = {
        id: '',
        parentsId: '', // 父级id
        name: '', // 项目名称
        showIndex: '', // 排序序号
        flag: '1', // "1"有下级 "0"无下级
        fieldType: 'title', //  "title"或者"content"
        type: '', // 项目类型
        hasScore: '', // 显示得分
        groupIndex: '' // 单选分组序号
      }
    },
    // 关闭小弹窗回调
    classXHandleClose(done) {
      this.clearXData()
      done && done()
    },
    // 关闭大弹窗回调
    classAHandleClose(done) {
      this.resetForm('classAdata')

      // console.log('classAdata清空')
      // console.log(this.classAdata.name)
      if (this.classAdata.id) {
        // console.log('没清掉')
        this.classAdata = {
          id: '',
          name: '',
          type: '',
          status: '0'
        }
      }
      // console.log(this.classAdata)
      // this.classAdata.id = ''
      this.classBdata = []
      this.classBradioValue = ''
      this.classBinfo = {
        type: '',
        classLevel: '',
        classAIsSingle: ''
      }
      // this.$confirm('确认关闭？')
      //          .then(_ => {
      done()
      // })
      // .catch(_ => {});
      // return
    },

    addConclusion(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const url = 'saveScoreConclusion'
          const data = {
            hospitalId: this.hospitalId,
            userId: this.userId,
            scoreId: this.conclusionForm.id,
            mincondition: this.conclusionForm.mincondition,
            maxcondition: this.conclusionForm.maxcondition,
            minimum: this.conclusionForm.minimum,
            maximum: this.conclusionForm.maximum,
            conclusion: this.conclusionForm.conclusion,
            showIndex: this.conclusionForm.showIndex
          }

          saveOrUpdateScoreConclusion(url, data).then(res => {
            if (res.code !== 9999) {
              this.selectScoreConclusionFun()
              this.resetForm('conclusionForm')
              this.$message.success('添加成功')
            } else {
              this.$message.error('添加失败')
            }
          })
        }
      })
    },

    // 删除结论
    deleteScoreConclusion(id) {
      this.$confirm('确认删除？')
        .then(_ => {
          const data = {
            id
          }
          deleteScoreConclusion(data).then(res => {
            if (res.code !== 9999) {
              this.selectScoreConclusionFun()
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
          })
        })
        .catch(_ => {})
    },
    // 清除指定数据
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields() && this.$refs[formName].clearValidate()
    },
    // 分页尺寸改变
    handleSizeChange(size) {
      this.pageSize = size
      this.selectList()
    },
    // 分页换页
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.selectList()
    },

    // 预览
    openAdd(row, index) {
      this.list.push(row)
      this.openAddDialog = true
    },
    // 关闭窗口
    handleClose(done) {
      this.list = []
      done()
    },

    // 评分预览
    getAddGrade(item) {
      const obj = this.scoreProcess(this.scoreSort([item]))
      this.addMark = obj.score
      if (item.scoreConclusionList) {
        this.addGrade = this.compareRange(item.scoreConclusionList, obj.score)
      }
    },
    addConfirm() {
      this.openAddDialog = false
      this.list = []
    },

    // 收取评分数据
    scoreSort(list) {
      let arr = []
      console.log(list, 'list')
      if (list.length > 0 && list) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].data) {
            arr.push(list[i].data)
          } else {
            if (list[i].scoreClassBList) {
              arr = arr.concat(this.scoreSort(list[i].scoreClassBList))
            }
          }
        }
      }
      return arr
    },
    // 评分数据处理
    scoreProcess(arr) {
      const indexArr = []
      let score = ''
      arr.forEach((el) => {
        if (el.indexOf('||') > 0) {
          indexArr.push(el.split('||')[0])
          if (!score) {
            score = parseInt(el.split('||')[1])
          } else {
            score += parseInt(el.split('||')[1])
          }
        } else {
          indexArr.push(el)
        }
      })
      return {
        index: indexArr.join(','),
        score: score
      }
    },
    // 获取比较分值的结论
    compareRange(list, score) {
      if (list.length === 0) {
        return '未录入描述信息，请联系医院管理员'
      }
      if (!score) {
        return ''
      }
      for (let i = 0; i < list.length; i++) {
        const max = score + list[i].maxcondition + list[i].maximum
        const min = score + list[i].mincondition + list[i].minimum
        if (this.calculator(min) && this.calculator(max)) {
          return list[i].conclusion
        }
      }
      return '所得分值无对应结论，请联系医院管理员'
    },
    // 字符串比较计算器
    calculator(str) {
      return new Function('return (' + str + ')')()
    }
  }
}
</script>

<style scoped>
.dialogStyle >>> .el-select {
  width: 100%;
}
.asFormLabel + div {
  width: 80%;
}
.scoreAddUpStyle {
  height: 400px;
  border: 1px solid #eee;
}
.ScoreManageStyle >>> .add_or_modify_dialogStyle .el-dialog__body {
  height: 95%;
}
.ScoreManageStyle >>> .add_or_modify_dialogStyle {
  height: 95vh;
}
.classbBtnGroup >>> .el-radio__input {
  display: none;
}
.classbBtnGroup >>> .el-radio {
  margin: 0 0 0 10px;
      text-overflow: ellipsis;
      white-space: nowrap;
       overflow: hidden;
}
.relationStyle >>> .el-form-item__content {
  width: 130px;
}
.conclusionStyle >>> .el-form-item__content {
  width: 80%;
}
.scrollbarStyle >>> .el-scrollbar__wrap {
  overflow-x: hidden;
}
/*  ::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }

    ::-webkit-scrollbar-thumb {
        background-color: #eee;
        border-radius: 3px;
    } */
</style>
<style scoped lang="scss">
  .card {
    margin: -1px 45px 0px 35px;
    padding: 10px 20px 0px 10px;
    border-top: 1px dashed #dcdfe6;
    border-radius: 4px;

    &-title,
    &-subTitle {
      margin-bottom: 10px;
      font-size: 15px;

      .right {
        display: flex;
        justify-content: flex-end;

        div {
          padding-left: 20px;
        }
      }

      .content {
        display: flex;
        align-items: center;
      }
    }

    &-subTitle {
      padding: 7px 0;
    }

    &-content {
      padding-left: 30px;
      font-size: 14px !important;

      .el-radio {
        min-width: 80px;
      }

      .radio-flex {
        .small-distance {
          margin-right: 0px;
          min-width: 60px !important;
        }

        .el-radio {
          min-width: 110px;
          margin: 0px 20px 20px 0px;
        }

        .small .el-checkbox {
          min-width: 110px;
        }

        .el-checkbox {
          margin: 0px 10px 20px 0px !important;
          min-width: 226.3px;
        }
      }

      .check {
        width: 750px;
      }

      &-result {
        margin: 0px 0px 20px;
      }

      .radio-box .el-radio {
        min-width: 200px;
        padding: 3px 0;
      }

      &-title {
        display: flex;
        flex: 0 0 45px;
        align-items: center;
      }

      &-subTitle {
        display: flex;
        flex: 0 0 45px;
      }

      .item {
        .row {
          padding-bottom: 20px;
        }
      }

      .inspect {
        width: 750px;
      }

      .project {
        width: 1000px;
        margin-top: 5px;
        margin-bottom: 15px;
      }

      .result-grade {
        .el-input {
          width: 280px;
        }
      }

      .result-score {
        padding-left: 20px;
        padding-right: 10px;

        .el-input {
          width: 50px;
        }
      }
    }
  }
</style>
